package com.lovo.util.utils;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对象转换工具
 */
public class ConvertBeanUtil {
    /**
     * 转换集合
     */
    public static <E,T> List<T> copyList(List<E> list, Class<T> clazz) {
        if (CollectionUtils.isEmpty(list) || clazz == null){
            return new ArrayList<>();
        }
        String oldOb = JSON.toJSONString(list);
        return JSON.parseArray(oldOb, clazz);
    }

    /**
     * 转换集合(进阶)
     */
    public static <E,T> List<T> copyList(List<E> list, Class<T> clazz, ConvertCallBack<E, T> convertCallBack) {
        if (CollectionUtils.isEmpty(list) || clazz == null){
            return new ArrayList<>();
        }
        return list.stream().map(e -> copy(e,clazz,convertCallBack)).collect(Collectors.toList());
    }

    /**
     * 转换对象
     */
    public static <E,T> T copy(Object ob, Class<T> clazz) {
        if (ob == null || clazz == null){
            return null;
        }
        String oldOb = JSON.toJSONString(ob);
        return JSON.parseObject(oldOb, clazz);
    }

    /**
     * 转换对象(进阶)
     */
    public static <E,T> T copy(E ob, Class<T> clazz,ConvertCallBack<E, T> convertCallBack) {
        if (ob == null || clazz == null){
            return null;
        }
        String oldOb = JSON.toJSONString(ob);
        T model = JSON.parseObject(oldOb, clazz);
        convertCallBack.converted(ob,model);
        return model;
    }

}
